import pika
import logging
import time
import sys
 
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s:%(message)s')
 
# RabbitMQ连接配置
rabbitmq_url = "amqp://user:password@172.16.168.58:5672/"
queue_name = "imgdesc"
 
def connect_to_rabbitmq():
   params = pika.URLParameters(rabbitmq_url)
   connection = pika.BlockingConnection(params)
   return connection
 
def main():
   sn = 0
   try:
       # 1. 连接到RabbitMQ服务器
       connection = connect_to_rabbitmq()
       channel = connection.channel()
       
       # 2. 声明持久化队列（参数必须与生产者一致）
       channel.queue_declare(queue=queue_name, durable=True)
       
       # 3. 设置QoS（公平分发）
       channel.basic_qos(prefetch_count=1)
       
       # 4. 消费消息
       def callback(ch, method, properties, body):
           nonlocal sn
           logging.info(f"Received a message: {body.decode()}")
           logging.info(f"Message Timestamp: {time.time()}")
           print(f"{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())} 当前记录为 {sn}")
           sn += 1
           
           # 模拟消息处理耗时
           time.sleep(1 * 0.001)
           
           # 手动确认消息
           ch.basic_ack(delivery_tag=method.delivery_tag)
       
       channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=False)
       
       logging.info(" [*] Waiting for messages. To exit press CTRL+C")
       channel.start_consuming()
   
   except pika.exceptions.AMQPConnectionError as e:
       logging.error(f"Failed to connect to RabbitMQ: {e}")
       sys.exit(1)
   except Exception as e:
       logging.error(f"An error occurred: {e}")
       sys.exit(1)
   finally:
       if connection:
           connection.close()
 
if __name__ == "__main__":
   main()
